package myJava;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

public final class DBConn {
    @Test
    //连接数据库
    public  static SqlSession getSqlSession() {
        String resource = "myXML/mybatis-config.xml";
        InputStream inputStream = null;
        SqlSession session = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            session = sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return session;
    }

    //校验用户信息
    public static Boolean check(Employee emp){
        SqlSession sqlSession = getSqlSession();
        try {
            //selectOne的第一个参数为Mapper.xml的mapper的namespace+id
            //参数二为映射的需要传入的参数
            Employee employee = sqlSession.selectOne(
                    "EmployeeMapper.selectEmployee_name", emp.getName());
            if (employee!=null && employee.getPassword().equals(emp.getPassword()))
                return true;
            else
                return false;
        } finally {
            free(sqlSession);
        }
    }

    //获取数据库的全部数据
    public static List<News> getAllNews(){
        SqlSession sqlSession = getSqlSession();
        List<News> list = sqlSession.selectList("EmployeeMapper.selectNews");
        free(sqlSession);
        return list;
    }

    public static News getNewsById(int id){
        SqlSession sqlSession = getSqlSession();
        News news = sqlSession.selectOne("EmployeeMapper.selectById",id);
        free(sqlSession);
        return news;
    }

    //向数据库添加数据,并且需要sqlSession.commit()
    public static void insertNews(News news){
        SqlSession sqlSession = getSqlSession();
        int result =sqlSession.insert("EmployeeMapper.insertNews",news);
        sqlSession.commit();
        free(sqlSession);
    }

    //删除新闻
    public static int deleteNews(int id){
        SqlSession sqlSession = getSqlSession();
        int result = sqlSession.delete("EmployeeMapper.deleteNewsById",id);
        sqlSession.commit();
        free(sqlSession);
        return result;
    }



    //修改新闻信息
    public static int upDataNewsById(News news){
        SqlSession sqlSession = getSqlSession();
        int res = sqlSession.update("EmployeeMapper.upDataNewsById",news);
        sqlSession.commit();
        free(sqlSession);
        return res;
    }


    //释放Sqlsession
    public static void free(SqlSession sqlSession){
        sqlSession.close();
    }
}
